/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import javax.inject.Inject;

import org.apache.commons.io.FileUtils;

import ru.irenproject.it.It;
import ru.irenproject.it.ItConsumer;
import ru.irenproject.it.ItInput;
import ru.irenproject.it.ItInputException;
import ru.irenproject.it.ItReader;
import ru.irenproject.it.XmlUtils;
import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Ids;
import ru.irenproject.store.Stash;
import ru.irenproject.store.Store;
import ru.irenproject.store.StoreFactory;

import com.google.protobuf.ByteString;
import com.google.protobuf.Message;

public final class FileProcessor extends AbstractThing implements Visual {
  public static final class OpenInput {
    public String fileName;
    public byte[] fileData;
  }

  public static final class OpenOutput {
    public String fileId;
  }

  public static final class CloseInput {
    public String fileId;
  }

  @Stash private UiProtos.FileProcessor.Builder $;
  private final StoreFactory fStoreFactory;
  private final ItInput fItInput;
  private final StoreCatalog fStoreCatalog;

  @Inject FileProcessor(StoreFactory storeFactory, ItInput itInput,
      StoreCatalog storeCatalog) {
    fStoreFactory = storeFactory;
    fItInput = itInput;
    fStoreCatalog = storeCatalog;
  }

  @Override public Message render() {
    return $.build();
  }

  @Action(badInput = ItInputException.class)
  public OpenOutput doOpen(OpenInput in) {
    try {
      Path temp = null;
      try {
        Path file;
        if (in.fileName != null) {
          Check.input(in.fileData == null);
          file = Paths.get(in.fileName);
          Check.input(Files.isReadable(file));
        } else if (in.fileData != null) {
          temp = Files.createTempFile(null, null);
          Files.write(temp, in.fileData);
          file = temp;
        } else {
          file = null;
        }

        ByteString fileId = store().generateId();
        Path storeDir = Utils.getStoreDirectory(fileId);

        boolean retainStoreDir = false;
        Files.createDirectories(storeDir);
        try {
          try (Store store = fStoreFactory.create(storeDir)) {
            boolean applyChanges = false;
            store.beginActivity();
            try {
              final Test[] test = new Test[1];
              if (file == null) {
                test[0] = store.create(Test.class);
              } else {
                fItInput.read(file, store, new ItConsumer() {
                  @Override public void consume(ItReader in) {
                    XmlUtils.checkName(in.root(), It.ELEM_IREN_TEST);
                    test[0] = in.readTest(in.root());
                  }
                });
              }

              TestDocumentEditor.createWithId(test[0], Store.ROOT_ID);

              store.dispatchEventsAndSave();
              applyChanges = true;
            } finally {
              store.endActivity(applyChanges);
            }
            store.persist();
            retainStoreDir = true;
          }
        } finally {
          if (!retainStoreDir) {
            FileUtils.deleteQuietly(storeDir.toFile());
          }
        }

        OpenOutput res = new OpenOutput();
        res.fileId = Ids.toHexString(fileId);
        return res;
      } finally {
        if (temp != null) {
          Files.delete(temp);
        }
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  @Action public void doClose(CloseInput in) {
    try {
      ByteString fileId = Ids.fromAlienHexString(in.fileId);
      Path storeDir = Utils.getStoreDirectory(fileId);
      Check.input(Files.isDirectory(storeDir));

      Store store = fStoreCatalog.get(fileId);
      if (store != null) {
        store.close();
        fStoreCatalog.remove(fileId);
      }

      FileUtils.deleteDirectory(storeDir.toFile());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
